/*
 * airplane.js
 * 自动站
 */
;
(function(call) {
    var main = {
        baseUrl: CafeJS.CXT,
        mapId: "tjMap",
        playList: null,
        datepicker: null,
        legendpicker: null,
        latestTime: null,
        router: {
        	getAwsStatData: 'cimiss-web/api',
        	stationMainTemplate: '/business/template/station-main.html',
        	productcfg: "/business/common/json/product.json"
        },
        init: function() {
            this.initView();
            this.bindEvt();
        },
        initView: function() {
        	var that = this;
        	that.getLatestTime();
        	that.initDatePicker();
			$.getJSON(that.router.productcfg, function (cfg) {
				that.initProductList(cfg);
			})
			$("#childMenu .airplane").bind("click",function () {
				if($(this).hasClass("active") && GIS.LayerControll.getLayerIds(that.mapId).join(",").indexOf("airplane_service") === -1){
					$.getJSON(that.router.productcfg, function (cfg) {
						that.initProductList(cfg);
					})
				}
			})
        },
        // 获取自动站最新实况时间
        getLatestTime: function() {
        	var that = this;
        	$.ajax({
        		url: this.router.getLatestTime,
        		type: 'GET',
        		dataType: 'json',
        		async: false
        	}).done(function(res){
        		if (res.isSuccess)
        			that.latestTime = res.data;
        	})
        },
		// 初始化产品列表
		initProductList: function(cfg) {
			var that = this;
			var params = {
				container: '.product-content.airplane',
				data: cfg.airplane,
				eleClick: function (ele, oldEle, selected) {
					var name = ele.ele_name;
					that.clearGridLayer("airplane");

					var pro = {
						name: '飞机报_ '+ name,
						time: that.calcStartTime(ele),
						bussitype: 'airplane',
						isGrid: false,
						ele: ele,
						isSK: true
					}
					if (selected) {
						// 增加产品图层
						that.addLayerManage(pro);
						that.queryEleData(ele, pro.time);
					}
				}
			};
			CafeJS.analysis(params);
		},
        // 初始化时间控件
        initDatePicker: function() {
        	var _this =  this;
        	this.datepicker = CafeJS.Datepicker({
                appendTo: "#datepicker-airplane",
				dateFmt: 'yyyy-MM-dd hh',
				dateType: 'H',
				type: 3,
                timeInterval: 3,
                customHm: [2,5,8,11,14,17,20,23],
                call: function(val) {
					_this.queryMultiEleData();
                },
            });
        	$("#datepicker-airplane").show();
        },
        // 初始化图例
    	initLegentpicker: function(ele, appendTo) {
    		var that = this;
    		var layers = that.getModels(ele);
    		var layerIds = [];
			$.each(layers,function(i,m){
    			layerIds.push(m.id);
			});
			CafeJS.Legentpicker({
				appendTo: appendTo,
				gisId: that.mapId,
				layerId: layerIds,
				totalWidth : 400,
				h_legend: 15,
				seq : 'decrease',
				productId: ele.color_id,
				isShowSlider : true
			});
		},
        // 初始化播放列表
    	initPlayList: function(pro){
    		var that = this;
    		var startTime = pro.time;

    		var layers = this.getModels(pro.ele);
    		var interval = pro.ele.interval || 3;
    		this.playList = CafeJS.Timeline3({
    			appendTo : "#a-m-timeline",
    			curDate : startTime,
    			type : 1,
    			pro: pro,
    			dateOpt: {
                	dateFmt : 'yyyy-MM-dd hh:mm',
                	timeInterval: interval,
                	customHm: []
                },
                timeInterval: interval,
    			layers: layers,
    			gisId : that.mapId,
    			call : function(pro){
    				CafeJS.layerManage.updateLayer(pro);
    				var ele = pro.ele;
    				that.queryEleData(ele, pro.time);
    			},
    			getPlayData: function(pro, timeArr){
    			}
    		});
    	},
        // 查询已选择要素
        queryMultiEleData: function() {
        	var that = this;
        	var pro, time;
    		$(".airplane .product-list li.active").each(function(i, ele){
    			pro = $(ele).data('pro');
    			time = that.calcStartTime(pro);
    			CafeJS.layerManage.updateLayerTime(time, 'airplane', null, pro.ele_id);
    			that.queryEleData(pro, time);
        	});
        },
        // 查询要素数据
        queryEleData: function(ele, time) {
        	var that = this;
        	var layerId = "airplane1";
            time = new Date(time);
            time.setHours(time.getHours() - 8);
            time = time.format('yyyyMMddhhmmss');
			that.clearGridLayer("airplane");
            var param = {
                "userId":"BETJ_xxzx_tjyth",
                "pwd":"xxzx_2000_GXW",
                "interfaceId":"getUparArdEleInRectByTimeRangeAndHeightRange",
                "elements":"Year,Mon,Day,Hour,Min,Second,Station_Id_C,Lat,Lon,Heigh_Alti,TEM,DPT,RHU,WIN_D,WIN_S,V11031",
                "timeRange":'['+time+','+time+']',
                "minFLayer":0,
                "maxFLayer":5000,
                "minLat":35.55,
                "maxLat":43.88,
                "minLon":108.71,
                "maxLon":123.56,
                "dataFormat":"json"
            }
            $.ajax({
                url: that.router.getAwsStatData,
                data: param,
                type: "GET",
                dataType: 'json',
                success: function (res) {
                    var arr = [];
                    if (res.DS && res.DS.length > 0) {
                        var data = res.DS;
                        for(var i=0;i<data.length;i++){
                            var station = {};
                            station["val"] = data[i].Heigh_Alti === "999999"?"":data[i].Heigh_Alti;
                            station["lat"] = Number(data[i]["Lat"]);
                            station["lon"] = Number(data[i]["Lon"]);
                            data[i]["lat"] = Number(data[i]["Lat"]);
                            data[i]["lon"] = Number(data[i]["Lon"]);
                            arr.push(station);
                        }
                        var option={
                            "layerId":layerId,
                            "iconUrl":'/business/common/css/images/airplane.png',
                            "key":"serviceType",
                            "xOffset":0,
                            "yOffset":0,
                            "id":layerId,
                            "data":data
                        };
                        var dataArr = {};
                        dataArr[0] = {};
                        dataArr[0]["airplane"] = arr;
                        var labelObj = {};
                        labelObj["airplane"] = { color: { R: 236, G: 105, B: 65, A: 1 }, scolor: "rgb(236,105,65)", lineWidth : 1, offx : 45, offy : 0, size : 16}
                        var dataObj = {
                            dataArr: dataArr,
                            eleTypes: ["airplane"],
                            statTypes: [0]
                        }
                        GIS.Station.showElements(that.mapId, dataObj, null, labelObj, null, null, {'cx': true});
                        GIS.Station.showDamage(that.mapId,option);

                        GIS.MouseEvent.Bind(that.mapId, layerId, null, function (point) {
                            var TEM = point.TEM;
                            TEM = TEM === "999999"?"-":TEM;
                            var DPT = point.DPT;
                            DPT = DPT === "999999"?"-":DPT;
                            var RHU = point.RHU;
                            RHU = RHU === "999999"?"-":RHU;
                            var WIN_D = point.WIN_D;
                            WIN_D = WIN_D === "999999"?"-":WIN_D;
                            WIN_D = WindUtil.getWindDire(WindUtil.calcWindDire(WIN_D)).CH;
                            var WIN_S = point.WIN_S;
                            WIN_S = WIN_S === "999999"?"-":WIN_S;
                            var content = `
                    	<div class="airplane-pop">
                    		<ul>
                    			<li><label>资料时间：</label><span>${point.Year}-${point.Mon}-${point.Day} ${point.Hour}:${point.Min}:${point.Second}</span></li>
                                <li><label>区站号：</label><span>${point.Station_Id_C}</span></li>
                                <li><label>高度：</label><span>${point.Heigh_Alti}</span></li>
                    			<li><label>温度：</label><span>${TEM}℃</span></li>
                    			<li><label>露点温度：</label><span>${DPT}℃</span></li>
                    			<li><label>相对湿度：</label><span>${RHU}%</span></li>
                    			<li><label>风：</label><span>${WIN_D},${WIN_S}m/s</span></li>
                    		</ul>
                    	</div>`;
                            return content;
                        });
                    } else {
						alert('该时间点无飞机报数据');
					}
                }
            })
        },
        // 增加产品图层
        addLayerManage: function(pro) {
        	var that =  this;
        	if (CafeJS.layerManage) {
        		CafeJS.layerManage.addLayer(pro);
        	} else {
        		CafeJS.layerManage = CafeJS.LayerManage({
        			appendTo : "#c-b-layermanage",
        			mapId: that.mapId,
        			proInfo: pro,
        			call: function(pro) {
        				CafeJS[pro.bussitype].initPlayList(pro);
    				},
    				more: function(pro){
    					CafeJS[pro.bussitype].stationView(pro);
    				},
    				close: function(pro) {
    					CafeJS[pro.bussitype].delLayer(pro);
    				}
        		})
        	}
			that.initLegentpicker(pro.ele, '.cafe-layer-item.active');
        },
        // 根据时间间隔获取开始时间
        calcStartTime: function() {
        	var time = new Date(this.datepicker.getVal());
			time.setMinutes(0);
        	return time.format('yyyy-MM-dd hh:mm');
        },
        // 删除图层后取消要素选择
        delLayer: function(pro) {
        	var eleid = pro.ele.ele_id;
    		$(".airplane .product-list li.active").each(function(){
        		if ($(this).data('eleid') == eleid){
        			$(this).click();
        			return false;
        		}
        	})
        },
        // 清除单要素GIS图层
		clearLayer: function(eleid) {
			GIS.Station.eleShowControl(this.mapId, [0,1,2,3,4,5], eleid, "delete");
		},
		// 清除格点GIS图层
		clearGridLayer: function(eleid) {
			var layerIds = [];
			GLMap.layerIds.forEach(function(layerId){
				if (layerId.lastIndexOf(eleid) != -1) {
					layerIds.push(layerId);
				}
			})
			GIS.LayerControll.deleteLayer(this.mapId, layerIds);
		},
		// 获取站点GIS图层id
		getStatLayerIds: function(){
			var layerIds = [];
			$(".airplane .product-list li.active").each(function(){
				var eleid = $(this).data("pro").type;
				[0,1,2,3,4,5].forEach(function(st){
					layerIds.push(eleid + st+"Stat");
				});
			});
			return layerIds;
		},
		// 获取要素样式
        getModels: function(ele){
    		var models = [];
    		$.each(ele.models.split(","),function(i,m){
    			var layerId = "airplane-layer-"+ m + "-" + ele.ele_id;
    			models.push({
    				type : m,
    				visible : true,
    				uv:false,
    				wd:ele.type == 'WIND' ? true : false,
    				id : layerId
    			});
    		});
    		return models;
    	},
        bindEvt: function() {
        },
    };
    if (typeof call === 'function') {
    	CafeJS.airplane = main;
        call(main);
    }

})(function(main) {
    CafeJS.models(['datepicker', 'legentpicker', 'legentconfig', 'ajax', 'squarelegend', 'timeLine3'], function() {
    	main.init();
    });
});
